package sen.myReport;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExcelExportHelper2 {
	
	private static final Logger LOG = LoggerFactory.getLogger(ExcelExportHelper2.class);
	
	private List<ExcelSheet> excelSheets;
	
	public ExcelExportHelper2(List<ExcelSheet> excelSheets) {
		this.excelSheets = excelSheets;
	}
	
	private HSSFWorkbook wb = null;
	public byte[] getExcelByteArray(){
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		wb = new HSSFWorkbook();
		
		for (int i = 0; i < excelSheets.size(); i++) {
			
			ExcelSheet es = excelSheets.get(i);
			String[] head = es.getHead();
			String sheetName = es.getLabelName();
			List<?> sheetData = es.getData();
			ExcelStyle[] styles = es.getExcelStyle();
			
			//创建Sheet
			Sheet sheet= wb.createSheet(sheetName);
			
			//添加表头
			Row row1 = sheet.createRow(0);
			for (int j = 0; j < head.length; j++) {
	            Cell cell = row1.createCell(j);
	            cell.setCellValue(head[j]);
	            setStyle(styles, cell);
			}
			
			//添加内容
			for (int k = 1; k <= sheetData.size(); k++) {
				Row row = sheet.createRow(k);
				
				List<?> rowData = (List<?>)sheetData.get(k-1);
				
				for (int l = 0; l < rowData.size(); l++) {
					
					Object content = rowData.get(l);
					
					Cell cell = row.createCell(l);
					setStyle(styles, cell);
					
					if(content == null) {
						cell.setCellValue("");
					} else if(content instanceof Double
							||content instanceof BigDecimal
							||content instanceof Float) {
						cell.setCellValue(Double.parseDouble(content.toString()));
					} else if(content instanceof Integer
							||content instanceof Long
							||content instanceof BigInteger) {
						cell.setCellValue(Long.parseLong(content.toString()));
					} else if(content instanceof ExcelFormula){
						cell.setCellFormula(((ExcelFormula)content).getContent());
					} else {
						cell.setCellValue(content.toString());
					}
				}
			}
		}
		
		try {
			wb.write(os);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(null != os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			wb = null;
		}
		return os.toByteArray();
	}
	
	private void setStyle(ExcelStyle[] styles, Cell cell) {
		for (int i = 0; i < styles.length; i++) {
			ExcelStyle es = styles[i];
			es.setWb(wb);
			es.setStyle(cell);
		}
	}
}